package com.dsunsoft.rtu.netty;

import com.dsunsoft.rtu.common.util.CommonUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<byte[]> {

    //处理服务端返回的数据
    @Override
    protected void channelRead0(ChannelHandlerContext context, byte[] data) throws Exception {
        SocketChannel socketChannel = (SocketChannel) context.channel();
        String remoteAddress = socketChannel.remoteAddress().toString();
        String hexData = CommonUtils.bytesToHexString(data);
        // 97 96 00 01 00 0B 07 03 08 00 11 00 25 00 38 00 80
        log.info("收到服务端消息: {}, 报文数据长度: {}, 16进制: {}", remoteAddress, data.length, hexData);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
